package edu.tyut.game.ui.community

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import edu.tyut.game.GameApplication
import edu.tyut.game.R
import edu.tyut.game.logic.model.Comment
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.utils.LogUtils

class CommentAdapter(private val context: Context, private val comments: MutableList<Comment>, private val viewModel: CommunityViewModel, private val fcId: Int): RecyclerView.Adapter<CommentAdapter.ViewHolder>(){

    private val tag = this::class.java.name

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
        // 头像
        val headImage: ImageView = view.findViewById(R.id.headImage)
        // 评论内容
        val comment: TextView = view.findViewById(R.id.comment_tv)
        // 点赞
        val like: ImageView = view.findViewById(R.id.like)
        // 点赞数量
        val likeCount: TextView = view.findViewById(R.id.likeCount)
        // 删除按钮
        val removeComment: ImageView = view.findViewById(R.id.remove_comment)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_comment_item, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val comment = comments[position]
        // 头像
        Glide.with(context).load("${ServiceCreator.BASE_URL}${comment.avatarPath}").into(holder.headImage)
        LogUtils.d(tag, "${ServiceCreator.BASE_URL}${comment.avatarPath}")
        // 评论内容
        holder.comment.text = "${comment.fromUsername} 回复 @${comment.toUsername}: ${comment.content}"
        // 点赞数量
        holder.likeCount.text = "${comment.likeCounts}"
        // 监听
        val commentView = LayoutInflater.from(context).inflate(R.layout.send_comment_item, null)
        val content: EditText = commentView.findViewById(R.id.content)
        val send: Button = commentView.findViewById(R.id.send)
        val dialog = AlertDialog.Builder(context)
            .setIcon(R.drawable.image5)
            .setTitle("友好评论😊")
            .setView(commentView)
            .create()
        content.addTextChangedListener {
            val con = content.text.toString().trim()
            send.isClickable = con.isNotBlank() && con.isNotEmpty()
        }
        send.setOnClickListener {
            // 默认会调用 send.isClickable = true
            val con = content.text.toString().trim()
            Log.i(tag, "$con isBank? ${con.isBlank()}")
            Toast.makeText(context, con, Toast.LENGTH_SHORT).show()
            dialog.dismiss()
            // 添加评论
            val username = GameApplication.loginUser?.username ?: "admin"
            val avatarPath = GameApplication.loginUser?.avatarPath ?: "/image/image.jpg"
            LogUtils.d(tag, avatarPath)
            val commentNew = Comment(0, username, avatarPath, fcId, con, username, comment.fromUsername, 0)
            // TODO 发送评论
            viewModel.postComment(commentNew)
        }
        send.isClickable = false
        holder.comment.setOnClickListener {
            LogUtils.d(tag, "点击发送消息... : $position")
            dialog.show()
        }
        // 点赞
        var likeFlag = false
        holder.like.setOnClickListener {
            if (!likeFlag) {
                Toast.makeText(context, "点赞", Toast.LENGTH_LONG).show()
                holder.like.setImageDrawable(
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.like_red
                    )
                )
                viewModel.addCommentLike(comment.id)
                holder.likeCount.text = "${holder.likeCount.text.toString().trim().toInt() + 1}"
            } else {
                Toast.makeText(context, "取消点赞", Toast.LENGTH_LONG).show()
                holder.like.setImageDrawable(
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.like
                    )
                )
                viewModel.addCommentLike(comment.id)
                holder.likeCount.text = "${holder.likeCount.text.toString().trim().toInt() - 1}"
            }
            likeFlag = !likeFlag
        }
        if (comment.fromUsername == GameApplication.loginUser?.username){
            holder.removeComment.visibility = View.VISIBLE
        }else{
            holder.removeComment.visibility = View.INVISIBLE
        }
        // TODO 删除评论，弹出一个dialog
        val dialogDel = AlertDialog.Builder(context)
            .setIcon(R.drawable.image5) // 设置标题的图片
            .setTitle("删除评论😊") // 设置对话框的标题
            .setMessage("是否删除这条评论🤔？") // 设置对话框内容
            .setNegativeButton("取消") { dia, which ->
                run {
                    Toast.makeText(context, "您点击了取消删除按钮", Toast.LENGTH_SHORT).show()
                    LogUtils.d(tag, "对话框，取消删除按钮: $which" )
                    dia.cancel()
                }
            }
            .setPositiveButton("确定"){ dia, which ->
                Toast.makeText(context, "评论删除成功😁", Toast.LENGTH_SHORT).show()
                LogUtils.d(tag, "对话框，确认删除按钮: $which" )
                dia.dismiss()
                viewModel.deleteComment(comment.id)
                comments.removeAt(position)
                this.notifyItemRemoved(position)
            }
            .create()
        holder.removeComment.setOnClickListener {
            dialogDel.show()
        }
    }

    override fun getItemCount() = comments.size
}